package com.example.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mapper.MessageMapper;
import com.example.pojo.Message;
import com.example.pojo.PageResult;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

import static com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaUpdate;

@Service
public class MessageService {
    @Resource
    private MessageMapper messageMapper;

    // 分页获取消息
    public PageResult<Message> getMessages(Integer receiverId, String receiverType, Integer page, Integer pageSize) {
        try {
            Page<Message> pageParam = new Page<>(page, pageSize);
            QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("receiver_id", receiverId)
                    .eq("receiver_type", receiverType)
                    .orderByDesc("create_time");

            // 使用自定义的 selectByReceiver 方法
            List<Message> messages = messageMapper.selectByReceiver(
                    receiverId,
                    receiverType,
                    (page - 1) * pageSize,
                    pageSize
            );

            // 获取总数
            Long total = messageMapper.selectCount(queryWrapper);

            return new PageResult<>(total.intValue(), messages);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("查询消息失败", e);
        }


//        // 1. 构建分页参数（MyBatis-Plus 自动计算 offset）
//        Page<Message> pageParam = new Page<>(page, pageSize);
//
//        // 2. 构建查询条件
//        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("receiver_id", receiverId)
//                .eq("receiver_type", receiverType)
//                .orderByDesc("create_time");
//
//        // 3. 执行分页查询（自动处理总数统计）
//        Page<Message> pageResult = messageMapper.selectPage(pageParam, queryWrapper);
//        // 4. 转换为自定义分页响应格式
//        return new PageResult<>(
//                (int) pageResult.getTotal(),
//                pageResult.getRecords()
//        );
    }

    // 获取未读消息数
    public int getUnreadCount(Integer receiverId,String receiverType) {
        return messageMapper.countUnread(receiverId, receiverType);
    }

    // 标记单个消息已读
    public void markMessagesAsRead(Integer messageId,Integer receiverId, String receiverType) {
       messageMapper.markAsRead(messageId,receiverId, receiverType);
    }
    public void markAllMessagesAsRead(Integer receiverId,String receiverType) {
      messageMapper.markAllAsRead(receiverId, receiverType);

    }
}